<!--
*@Author: QWP
*@Description: 公文编辑
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog v-bind="$attrs"
    destroyOnClose
    :confirmLoading="loading"
    :hideBtns="isCheck ? ['submit'] : []"
    @submit="submit"
    @close="dialogClose">
    <u-flow-tab activeKey="1"
      :show="isValue(form.status)"
      :isAudit="form.status == 2"
      :isAuditPage="route.params.pType == '2'"
      :params="{ type: 'income_doc', ...current}"
      ref="auditRef"
      v-bind="$attrs"
      @back="getAuditData">
      <a-tab-pane key='1' tab="基本信息">
        <a-row>
          <u-form :elements="formEls"
            :model="form"
            :gutter="0"
            :disabled="isCheck"
            ref="formRef"
            class="u-doc-iconme-form">
            <template #fileNoChar>
              <a-input-group compact>
                <a-select v-model:value="form.fileNoChar" 
                  :options="fileNoChars"
                  style="width: calc(50% - 38px)" />
                <div style="height: 32px; line-height: 32px;">
                  〔 {{ form.fileNoYear }} 〕
                </div>
                <a-form-item-rest>
                  <a-input v-model:value="form.fileNoOrder" 
                    addonAfter="号" 
                    style="width: calc(50% - 38px)" id="fileNoOrder"/>
                </a-form-item-rest>
              </a-input-group>
            </template>
          </u-form>
        </a-row>
      </a-tab-pane>
    </u-flow-tab>
    <template #footerBefore>
      <template v-if="!form['status'] || ['1', '4'].includes(form['status'] + '')">
        <u-icon-button itype="save" @click="submit('up')" :loading="loading">保存并上报</u-icon-button>
      </template>
      <!-- <template v-if="route.params.pType == '2' && form['status'] == '2' && $attrs['adstatus'] != '1'"> -->
      <template v-if="route.params.pType == '2' && form['status'] == '2' && isAudited == true">
        <u-icon-button itype="approve" @click="auditAbout('2')">批准</u-icon-button>
        <u-icon-button itype="clsoe" @click="auditAbout('3')">退回</u-icon-button>
        <!-- <u-audit-button></u-audit-button> -->
        <!-- <u-audit-back-button></u-audit-back-button> -->
        <!-- <u-icon-button itype="reansmit">转发</u-icon-button> -->
      </template>
    </template>
  </u-dialog>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, watch, useAttrs } from 'vue' 
import { useRoute, useRouter } from 'vue-router'
import { useBaseStore, useLoginStore } from '@/store'
import { storeToRefs } from 'pinia'
import { _IFormEl, _IExtra } from '@/src/components/common/form/interface';
import { FormInstance, FormItemProps } from 'ant-design-vue';
import { HomeOutlined, FileTextOutlined, UploadOutlined } from '@ant-design/icons-vue';
import { isSel1 } from '@/common/model/base'
import { nullC, alertC, messageC, isValue } from '@/util/common'
import { cloneDeep } from 'lodash'
import { useAuditAbout, IAuditParams } from '@/hooks/useAudit'
// import * as incomeApi from '@/service/officialDoc/incomeDoc'
import * as publishDocApi from '@/service/officialDoc/publishDoc'
// import * as unitApi from '@/service/system/unit'
import dayjs from 'dayjs';
const props = defineProps<{
  current?: object,
  isAudited?: boolean,
}>()

const attrs = useAttrs()

const route = useRoute()
const { INC_NODE, EMERGENCY_DEGREE, OPEN_FORM, fileNoChars } = storeToRefs(useBaseStore())
const { userInfo } = storeToRefs(useLoginStore())

const emits = defineEmits(['success'])

const baseData = reactive({
  unitData: []
})

const isCheck = computed(() => ['2', '3'].includes(form.value.status + ''))

const loading = ref<boolean>(false)
const auditRef = ref<FormInstance>()
const formRef = ref<FormInstance>()
const form = ref({
  fileNoYear: dayjs().format('YYYY')
})
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '120px',
  colon: false
}
const formEls: Array<_IFormEl> = [
  // { label: '收文标题', key: 'title', col: { span: 24 }, element: 'input', 
  //   formItemProps: { ...formItemProps, required: true } 
  // },
  { label: '来文电单位', key: 'incdocunitname', col: { span: 8 }, element: 'input', 
    formItemProps: { ...formItemProps, required: true } 
  },
  { label: '收文时间', key: 'acceptDate', col: { span: 8 }, element: 'datepicker', 
    formItemProps: { ...formItemProps, required: true },
  },
  { label: '原文号', key: 'docnumber', col: { span: 8 }, element: 'input', 
    formItemProps: { ...formItemProps, autoLink: false }, 
  },
  { label: '是否涉密', key: 'isSecretRelated', col: { span: 8 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true, }, 
    componentProps: { options: isSel1() }
  },
  { label: '等级', key: 'urgencyDegree', col: { span: 8 }, element: 'select', 
    formItemProps: { ...formItemProps, }, 
    componentProps: { options: EMERGENCY_DEGREE.value }
  },
  { label: '收文号', key: 'fileNoChar', col: { span: 8 }, element: 'slot',
    formItemProps: { 
      ...formItemProps, required: true, //autoLink: false, 
    } 
  },
  { label: '内容摘要', key: 'docabs', col: { span: 24 }, element: 'textarea', 
    formItemProps: { ...formItemProps, class: 'u-view-text' }, 
  },
  { label: '分文意见', key: 'nbyj', col: { span: 24 }, element: 'text', 
    formItemProps: { ...formItemProps, class: 'u-view-text' }, 
  },
  { label: '领导批示', key: 'ldps', col: { span: 24 }, element: 'text', 
    formItemProps: { ...formItemProps, class: 'u-view-text'}, 
  },
  { label: '阅办情况', key: 'ybqk', col: { span: 24 }, element: 'text', 
    formItemProps: { ...formItemProps, class: 'u-view-text'}, 
  },

  // { label: '来文份数', key: 'no', col: { span: 12 }, element: 'input', 
  //   formItemProps: { ...formItemProps, required: true, }, 
  // },
  // { label: '收文字号', key: 'acceptWordsize', col: { span: 12 }, element: 'input', 
  //   formItemProps: { ...formItemProps, required: true } 
  // },
  // { label: '拟办意见', key: 'nbyj', col: { span: 12 }, element: 'text', 
  //   formItemProps: { ...formItemProps, class: 'u-view-text' }, 
  // },
  // { label: '领导批示', key: 'ldps', col: { span: 12 }, element: 'text', 
  //   formItemProps: { ...formItemProps, class: 'u-view-text'}, 
  // },
  // { label: '部门办理情况', key: 'bmblqk', col: { span: 24 }, element: 'text', 
  //   formItemProps: { ...formItemProps, class: 'u-view-text'}, 
  // },
  // { label: '备注', key: 'contents', col: { span: 24 }, element: 'textarea', 
  //   formItemProps: { ...formItemProps, class: 'u-view-text' }, 
  // },
  { label: '附件', key: 'fileList', col: { span: 24 }, element: 'file', 
    formItemProps: { ...formItemProps, class: 'u-view-text', required: true }, 
    componentProps: {
      fileParams: {biztype: '4', bucket: 'INC', },
      labelWidth: '120px' 
    }
  },
]

// 保存提交
const submit = async(type?: string) => {
  try {
    await formRef.value.form.validate()
  } catch (error) {
    alertC("请先表单信息填写完毕!");
    return
  }

  const url = form.value.keyid ? 'update' : 'add';
  if((form.value['fileList'] || []).length != 0) {
    form.value.fileList.forEach(item => item.fileAttribute = 1)
  }
  
  // await alertC("确认保存？", 'confirm')
  loading.value = true;
  try {
    const res = await publishDocApi[url](form.value)
    if(res.code == 0) {
      if(type != 'up') {
        messageC(res.msg, "success")
      }
      if(url == 'add') {
        form.value.keyid = res.data['keyid']
        form.value.status = res.data["status"];
      }
      if(type == 'up') {
        await auditAbout('1')
      }
      dialogClose()
      emits('success')
    }
    else {
      messageC(res.msg, "error")
    }
  } catch (error) { }
  loading.value = false;
}

// 上报、审核、退回
const auditAbout = async (type: string) => {
  loading.value = true;
  const auditParams: IAuditParams = {
    type: 'income_doc',
    selDatas: [form.value],
    confirm: false,
    isDialog: false
  }
  try {
    const res = await useAuditAbout(type, auditParams, auditRef)
    if(res.error == 200) {
      dialogClose()
      emits('success')
    }
  } catch (error) {}
  loading.value = false;
}

// 新增初始化元数据
const initFormInfo = () => {
  form.value = {
    fileNoYear: new Date().getFullYear(),
    fkunitsid: userInfo.value.unitId,
    fkdeptid: userInfo.value.deptId,
    redeptname: userInfo.value.deptName,
    username: userInfo.value.name,
    docType: 2 // 收文
  }
}

// 获取回显信息
const echoInfo = async () => {
  loading.value = true;
  try {
    const res = await publishDocApi.query(props.current['keyid']);
    if(res.code == 0) {
      // 发文信息
      const busiTIncDoc = res.data['busiTIncDoc'] || {}

      form.value = res.data;
    }
  } catch (error) { }
  loading.value = false;
}

// 判断是否存在值
const justValue = (key: string, data: objetc) => {
  if(!form.value[key]) {
    form.value[key] = data[key];
  }
}

// 获取签批信息
const getAuditData = (data: any[]) => {
  let result = {};
  data.forEach(item => {
    if(!result[item['usertaskname']]) {
      result[item['usertaskname']] = [];
    }
    result[item['usertaskname']].push(item)
  })

  const group = (items) => {
    let tRes = {};
    items.forEach(o => {
      if(!tRes[o['username']]) {
        tRes[o['username']] = [];
      }
      tRes[o['username']].push(o)
    })
    
    let aas = [];
    for(let k in tRes) {
      let kks = tRes[k] || []
      let name = nullC(kks[kks.length == 0 ? 0 : kks.length - 1]['username'])
      let msg = nullC(kks[kks.length == 0 ? 0 : kks.length - 1]['msg'])
      // aas.push(name + (msg ? `(${msg})` : ''))
      aas.push(name)
    }

    return aas.join(',                                       ')
  }

  for(let key in result) {
    let tRes = result[key] || []
    let current = formEls.find(i => i.label == key);
    if(current) {
      form.value[current['key']] = group(tRes)
    }
  }
}

// 弹窗关闭
const dialogClose = () => {
  form.value = {};
  formRef.value.form.resetFields();
}

watch(()  => attrs.open, (nval, oval) => {
  if(nval == false) return

  if(props.current['keyid']) {
    echoInfo()
  }
  else {
    initFormInfo()
  }
})
</script>

<style lang='scss' >
.u-doc-iconme-form {
  &>.ant-row {
    $borderColor: #EA0000;
    border-bottom: 1px solid $borderColor ;
    border-right: 1px solid $borderColor ;
    .ant-form-item {
      margin-bottom: 0;
      height: 100%;
      .ant-form-item-row {
        height: 100%;
        &>.ant-col {
          border: 1px solid $borderColor;
          border-bottom: unset;
          border-right: unset;
          border-collapse: collapse;
          background: rgba(234,0,0,0.05);
        }
        .ant-form-item-label {
          label {
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            color: #EA0000;
            line-height: 22px;
            text-align: left;
            font-style: normal;
            text-transform: none;
          }
        }
        .ant-form-item-control-input {
          height: 100%;
        }
      }
      
      .ant-input-suffix {
        color: #AAAAAA
      }
    }
    .u-view-text {
      .ant-form-item-row {
        height: auto;
        .ant-form-item-label {
          line-height: 60px;
        }
      }
    }
  }
  .ant-upload-list-item-container {
    .ant-col {
      border: none !important;
      background: unset !important;
    }
  }
}
</style>